package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.entity.sysstation.StationPx;
import com.qingcloud.adminbackend.entity.sysstationmo.*;
import com.qingcloud.adminbackend.mapper.SysDomainMapper;
import com.qingcloud.adminbackend.mapper.SysStationMoMapper;
import com.qingcloud.adminbackend.service.ISysStationMoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * <p>
 * 监测点监测对象 服务实现类
 * </p>
 *
 * @author luozehua
 * @since 2019-04-16
 */
@Service
public class SysStationMoServiceImpl extends ServiceImpl<SysStationMoMapper, SysStationMo> implements ISysStationMoService {

    //文件服务器路径
    @Value("${file.rootpath}")
    private String ROOTPATH;

    @Resource
    private SysStationMoMapper sysStationMoMapper;

//    @Resource
//    private TdWcenterThresholdDefaultMapper thresholdDefaultMapper;
//
//    @Resource
//    private TdWcenterThresholdMapper thresholdMapper;

    @Resource
    private SysDomainMapper domainMapper;

    /**
     * 获取所有楼宇的名称
     *
     * @return
     */
    @Override
    public List<StationMoDTO> getAllBuildNames(String streetName, String domainId) {
        //根据道路的名称查询道路的ID
        String addressId = sysStationMoMapper.getRoadId(streetName, domainId);
        if (StrUtil.isNotBlank(addressId)) {
            return sysStationMoMapper.getAllBuildNames(addressId);
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * 根据楼宇名称查询下面所有的楼层
     *
     * @param buildName
     * @return
     */
    @Override
    public List<StationMoDTO> getAllFloorNames(String streetName, String buildName, String domainId) {
        //根据道路的名称查询道路的ID
        String addressId = sysStationMoMapper.getRoadId(streetName, domainId);
        if (StrUtil.isNotBlank(addressId)) {
            return sysStationMoMapper.getAllFloorNames(buildName, domainId);
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * 根据所有楼层名称查询房间
     *
     * @param floorName
     * @return
     */
    @Override
    public List<StationMoDTO> getAllRoomNames(String streetName, String buildName, String floorName, String domainId) {
        //根据道路的名称查询道路的ID
        String addressId = sysStationMoMapper.getRoadId(streetName, domainId);
        if (StrUtil.isBlank(addressId)) {
            return Collections.emptyList();
        }
        List<SysStationMo> sysStationMos = sysStationMoMapper.selectByMap(ImmutableMap.of("capation", buildName, "domain_id", domainId, "mo_type", 1));
        if (CollUtil.isEmpty(sysStationMos)) {
            return Collections.emptyList();
        }
        return sysStationMoMapper.getAllRoomNames(floorName, domainId);
    }

    /**
     * 根据区域查询街道
     *
     * @param domainId
     * @return
     */
    @Override
    public List<StationMoDTO> getStreetNames(String domainId) {
        return sysStationMoMapper.getStreetNames(domainId);
    }

    /**
     * 监测位置父级
     *
     * @return
     */
    @Override
    public List<Map> getStationMoFather() {
        List<SysStationMo> stationMos = sysStationMoMapper.getStationMoFather();
        List<Map> resultList = new ArrayList<>();
        for (SysStationMo stationMo : stationMos) {
            // 组装所有船
            if (stationMo.getId().length() <= 5) {
                Map<String, Object> moMapLev1 = new HashMap<>();
                moMapLev1.put("value", stationMo.getId());
                moMapLev1.put("label", stationMo.getCapation());
                moMapLev1.put("children", null);
                resultList.add(moMapLev1);
            }
            // 组装船对应的所有楼层
            if (stationMo.getParentId() != null && stationMo.getParentId().trim().length() > 0) {
                String lev1Id = stationMo.getId().substring(0, 5);
                Map<String, Object> moMapLev1 = resultList.get(resultList.size() - 1);

                List<Map> lev2List = (List<Map>) moMapLev1.get("children");

                if (stationMo.getParentId().equals(lev1Id)) {
                    if (lev2List == null) {
                        lev2List = new ArrayList<>();
                    }
                    Map<String, Object> moMapLev2 = new HashMap<>();
                    moMapLev2.put("value", stationMo.getId());
                    moMapLev2.put("label", stationMo.getCapation());
                    moMapLev2.put("children", null);
                    lev2List.add(moMapLev2);
                    moMapLev1.put("children", lev2List);
                }
                // 组装楼层对应的区域
                if (lev2List.size() > 0) {
                    Map<String, Object> lev2Map = lev2List.get(lev2List.size() - 1);
                    String lev2Id = (String) lev2Map.get("value");

                    List<Map> lev3List = (List<Map>) lev2Map.get("children");
                    if (stationMo.getParentId().equals(lev2Id)) {
                        if (lev3List == null) {
                            lev3List = new ArrayList<>();
                        }
                        Map<String, Object> moMapLev3 = new HashMap<>();
                        moMapLev3.put("value", stationMo.getId());
                        moMapLev3.put("label", stationMo.getCapation());
                        lev3List.add(moMapLev3);
                        lev2Map.put("children", lev3List);
                    }
                }
            }
        }
        return resultList;
    }

    /**
     * 监测位置所属
     *
     * @return
     */
    @Override
    public List<SysStationMo> getStationMoBelong() {
        List<SysStationMo> stationMos = sysStationMoMapper.getStationMoBelong();
        return stationMos;
    }

    /**
     * 监测位置类型
     *
     * @return
     */
    public List<SysStationMo> getStationMoType() {
        List<SysStationMo> stationMos = sysStationMoMapper.getStationMoType();
        return stationMos;
    }

    /**
     * 添加监测位置
     *
     * @return 新增加的监测位置的ID
     */
    @Transactional(rollbackFor = Throwable.class)
    public AddStationMo addStationMo(AddStationMo addStationMo) {
        // 查找MoId
        if (addStationMo.getParentId() == null || addStationMo.getParentId().length() < 1) {
            //楼宇为空,创建楼宇，楼层，房间
            Long maxBuildId = sysStationMoMapper.findMaxBuildId();
            if (maxBuildId == null) {
                maxBuildId = 9999L;
            }
            String moId = String.valueOf(maxBuildId + 1);
            addStationMo.setMoId(moId);
        } else {
            BigInteger maxBuildId = sysStationMoMapper.findMaxMoId(addStationMo.getParentId());
            if (Objects.isNull(maxBuildId)) {
                maxBuildId = new BigInteger(addStationMo.getParentId() + "09999");
            }
            String moId = String.valueOf(maxBuildId.add(BigInteger.ONE));
            addStationMo.setMoId(moId);
        }
        // 组装属性Json字符串格式
        Map<String, Object> attrMap = new HashMap<>();
        Map<String, Object> attrMapEn = new HashMap<>();
        for (AddStationMoAttr attr : addStationMo.getAttrList()) {
            if (attr.getValue() != null) {
                attrMap.put(attr.getKey(), attr.getValue());
            }
            if (attr.getValueEn() != null) {
                attrMapEn.put(attr.getKey(), attr.getValueEn());
            }
        }
        JSONObject jsonAttr = new JSONObject(attrMap);
        JSONObject jsonAttrEn = new JSONObject(attrMapEn);

        sysStationMoMapper.addStationMo(addStationMo);
        // 如果是船则添加默认阈值
        if (addStationMo.getMoId().length() == 5) {

//            addThreshold(addStationMo.getMoId());
        }
        // 添加属性
        if (jsonAttr.size() > 0 || jsonAttrEn.size() > 0) {
            sysStationMoMapper.addStationAttr(addStationMo.getMoId(), jsonAttr.toString(), jsonAttrEn.toString());
        }
        return addStationMo;
    }

    /**
     * 功能描述: 添加默认阈值
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2020/5/15 11:15
     */
//    public void addThreshold(String moId) {
//        QueryWrapper<TdWcenterThreshold> query = new QueryWrapper<>();
//        query.eq("project_id", moId);
//        Integer count = thresholdMapper.selectCount(query);
//        if (count == null || count <= 0) {
//            //没有，则插入默认配置
//            List<TdWcenterThresholdDefault> defaults = thresholdDefaultMapper.selectList(new QueryWrapper<>());
//            defaults.forEach(e -> {
//                TdWcenterThreshold threshold = new TdWcenterThreshold();
//                BeanUtil.copyProperties(e, threshold);
//                threshold.setProjectId(moId);
//                threshold.setLevel(e.getLevel());
//                threshold.setTime(LocalDateTime.now());
//                thresholdMapper.insert(threshold);
//            });
//        }
//    }

    /**
     * 保存监测数据图片
     *
     * @param stationMo 已经生成了ID的监测对象
     */
    public void saveMoImage(AddStationMo stationMo) throws IOException {
        String moId = stationMo.getMoId();
        //moId不能为空
        if (StrUtil.isBlank(moId)) {
            return;
        }
        //检查目录是否已经存在
        String parentPath = ROOTPATH + moId.substring(0, 5);
        Path dir = Paths.get(parentPath);
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }
        if (StrUtil.isNotBlank(stationMo.getMoThumb())) {
            String fileSuffix = stationMo.getMoThumb().substring(stationMo.getMoThumb().lastIndexOf("."));
            //上传了缩略图，移动缩略图为指定文件
            FileUtil.move(new File(ROOTPATH + stationMo.getMoThumb()), new File(parentPath + "/" + moId + fileSuffix), true);
        }
        if (StrUtil.isNotBlank(stationMo.getPicHorizontal())) {
            String fileSuffix = stationMo.getPicHorizontal().substring(stationMo.getPicHorizontal().lastIndexOf("."));
            //上传了缩略图，移动缩略图为指定文件
            FileUtil.move(new File(ROOTPATH + stationMo.getPicHorizontal()), new File(parentPath + "/" + moId + "h" + fileSuffix), true);
        }
        if (StrUtil.isNotBlank(stationMo.getPicVertical())) {
            String fileSuffix = stationMo.getPicVertical().substring(stationMo.getPicVertical().lastIndexOf("."));
            //上传了缩略图，移动缩略图为指定文件
            FileUtil.move(new File(ROOTPATH + stationMo.getPicVertical()), new File(parentPath + "/" + moId + "v" + fileSuffix), true);
        }
    }

    /**
     * 删除监测位置
     *
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public Integer deleteStationMo(String moId) {
        List<SysStationMo> stationMoList = sysStationMoMapper.getStationMo(moId);
        List<String> moIds = new ArrayList<>();
        for (SysStationMo stationMo : stationMoList) {
            moIds.add(stationMo.getId());
        }
        // 判断是否绑定了监测点
        List<SysStationMo> bindList = sysStationMoMapper.findBindStation(moIds);
        if (bindList.size() > 0) {
            return -1;
        }
        sysStationMoMapper.deleteStationMoArticle(moId);
        sysStationMoMapper.deleteStationMoAttr(moId);
        Integer result = sysStationMoMapper.deleteStationMo(moId);
        return result;
    }

    /**
     * 查询点位
     *
     * @return
     */
    public List<StationPx> getStationMoPx(String moId) {
        // 查询位置信息
        List<SysStationMo> stationMoList = sysStationMoMapper.getStationMo(moId);
        // 获取位置Id
        List<String> moIds = new ArrayList<>();
        for (SysStationMo stationMo : stationMoList) {
            moIds.add(stationMo.getId());
        }
        // 获取位置绑定的监测点
        List<StationPx> bindList = sysStationMoMapper.findStationPx(moIds);

        return bindList;
    }

    /**
     * 监测点所属，类型，种类
     *
     * @return
     */
    public StationMoVO getStationMoInfo(String moId) {
        // 获取AddressId
        String addrId = sysStationMoMapper.getAddressId(moId.substring(0, 5));
        // 获取所属公司信息
        StationMoVO addressMo = sysStationMoMapper.getAddressInfo(addrId);
        // 获取监测位置信息
        StationMoVO stationMo = sysStationMoMapper.getStationMoInfo(moId);
        // 组装数据
        stationMo.setAddress(addressMo.getCapation());
        stationMo.setAddressId(addressMo.getAddressId());
        stationMo.setFullDomainName("");
        if (Objects.nonNull(stationMo.getDomainId())) {
            stationMo.setFullDomainName(domainMapper.findFullNameByDistrict(stationMo.getDomainId()));
        }
        return stationMo;
    }
}
